/*
 * 文 件 名:  AuthFilter.java
 * 版    权:   深圳埃思欧纳信息咨询有限公司版权所有. YYYY-YYYY,  All rights reserved
 * 描    述:   <描述>
 * 修 改 人:  honny.huang
 * 修改时间: 2011-4-14
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.ue.log.LogManager;

/**
 * <一句话功能简述> <功能详细描述>
 *
 * @author honny.huang
 * @version [版本号, 2011-4-14]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */

public class AuthFilter implements Filter
{
	/**
     * 来源类型 5 手机版actionMethod个人用户
     */
    public static final String SOURCETYPE_A3G_PO_SESSION = "5";

    /**
     * 来源类型 5 手机版jsp个人用户
     */
    public static final String SOURCETYPE_A3g_JSP = "6";

    /**
     * 来源类型 5 手机版actionMethod个人用户是否通过
     */
    public static final String SOURCETYPE_A3G_SENIOR_USER = "7";

    Map<String, String> sourceType5Map = null;

    Map<String, String> sourceType6Map = null;

    Map<String, String> sourceType7Map = null;

	
	
	public static void main(String[] args) 
	{
		AuthFilter authFilter = new AuthFilter();
//		authFilter.doFilter(req, res, filterChain);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res,FilterChain filterChain) throws IOException, ServletException 
	{
		    //关注ue.config.java
		
		    HttpServletRequest request = (HttpServletRequest) req;
	        HttpServletResponse response = (HttpServletResponse) res;
	        String requestUrl = request.getRequestURL().toString();  //  不包含请求参数http://localhost:8080/jqueryWeb/resources/request.jsp
	        requestUrl = requestUrl.toLowerCase();  
	        String queryString = request.getQueryString();  //  请求参数a=1&b=2
	        String loginUrl = "login.jsp";

	        String contextPath = request.getContextPath();  //  工程名/jqueryWeb
	        String jspLoginUrl = "/login.jsp";
	        String requestURI = request.getRequestURI();   // /jqueryWeb/resources/request.jsp?a=1&b=2
	        String realUrlPath = StringUtils.replaceOnce(requestURI, contextPath, "");
//	        String beforeURL = realUrlPath + "?" + request.getQueryString();
	        String beforeURL = realUrlPath + "?" + getQueryString(request);

	      

	        if (requestUrl.indexOf(".jsp") > 0)
	        {
	            String jspPath = requestUrl.substring(requestUrl.lastIndexOf("/") + 1);

//	            UserInfoPo userInfo = (UserInfoPo) UserCacheManager.getUserCache(WebConstants.A3GLOGINUSERINFO,request);
//	            if (sourceType6Map.containsKey(jspPath))
//	            {
//
//	                if (null == userInfo)
//	                {
//	                	UserCacheManager.setUserCache(WebConstants.BEFOREPAGE,beforeURL,request);
//	                    // 转向登录页面
//	                    toPage(request, response, jspLoginUrl);
//	                    return;
//	                }
//	            }

	        }
	        else
	        {
	            if (null != queryString)
	            {
	                String strAction;
	                if (queryString.indexOf("=") >= 0)
	                {
	                    strAction = queryString.substring(0, queryString.indexOf("="));
	                }
	                else
	                {
	                    strAction = queryString;
	                }
//	                String method = request.getParameter(WebConstants.ACTION);
//	                String authMethod = strAction + method;
//	                
//	                UserInfoPo userInfo = (UserInfoPo) UserCacheManager.getUserCache(WebConstants.A3GLOGINUSERINFO,request);
//	                // 判断操作该功能是否登录
//	                if (sourceType5Map.containsKey(authMethod))
//	                {
//	                    if (null == userInfo)
//	                    {
////	                    	UserCacheManager.setUserCache(WebConstants.BEFOREPAGE,beforeURL,request);
//	                        // 转向登录页面
//	                        toPage(request, response, loginUrl);
//	                        return;
//	                    }
//	                }
//
//	                // 判断用户是否需要通过实名认证才能操作
//	                if (sourceType7Map.containsKey(authMethod))
//	                {
//	                    // 用户已登录,做过滤
//	                    if (null != userInfo)
//	                    {
//	                        A3gAuthActionService actionService = new A3gAuthActionService();
//	                        // 不是特殊用户、HR、或有合格简历用户,提示
//	                        if (!actionService.checkIsRealNameUser(userInfo))
//	                        {
//	                        	UserCacheManager.setUserCache(WebConstants.BEFOREPAGE,beforeURL,request);
//	                            // 转向登录页面
//	                            toPage(request, response, loginUrl);
//	                            return;
//	                        }
//	                    }
//	                }

	            }
	        }
	        filterChain.doFilter(req, res);
		// TODO Auto-generated method stub
		
	}
	
	 /**
     * 获得地址参数
     * 
     * @param request
     * @return
     */
    public String getQueryString(HttpServletRequest request)
    {
        StringBuffer result = new StringBuffer();
        Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements())
        {
            String name = (String) parameterNames.nextElement();
            if (name.matches("[a-zA-Z]+Action"))
            {
                result.insert(0, name + "=" + request.getParameter(name));
            }
            else
            {
 //         	    result.append("&" + name + "=" + request.getParameter(name));
                try 
                {
					result.append("&" + name + "=" +  URLEncoder.encode(request.getParameter(name),"UTF-8"));
				} catch (UnsupportedEncodingException e)
				{
					e.printStackTrace();
				}
            }
        }
        return result.toString();
    }

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
	
	/**
     * 转向页面
     * @param request
     * @param response
     */
    protected void toPage(HttpServletRequest request, HttpServletResponse response, String toPageUrl)
    {
        if (StringUtils.isBlank(toPageUrl))
        {
            toPageUrl = "/";
        }

        // 转到错误页面
        RequestDispatcher rd = request.getRequestDispatcher(toPageUrl);
        try
        {
            LogManager.info("Dispatcher to page:[" + toPageUrl + "]!");
            rd.forward(request, response);
        }
        catch (Exception e)
        {
            LogManager.warn("Dispatcher to page:[" + toPageUrl + "] error!");
            LogManager.warn(e);
        }
    }

/**
1、request的相关常用用法
request.getRequestURI() /jqueryWeb/resources/request.jsp
request.getRequestURL() http://localhost:8080/jqueryWeb/resources/request.jsp
request.getContextPath()/jqueryWeb
request.getServletPath()/resources/request.jsp
request.getRemoteHost()  // 登录IP


注： resources为WebContext下的目录名
      jqueryWeb 为工程名
Request.getRequestURL返回的是请求的全部，包括Http协议，端口号，servlet名字和映射路径，但它不包含请求参数。
request.getRequestURI得到的是request URL的部分值，并且web容器没有decode过的 


2、request.getQueryString() 的怎么用？

比如发送
http://localhost/test.do?a=b&c=d&e=f
得到的是
a=b&c=d&e=f
* */
    
}
